<template>
  <div class="about-master-container">
    <base-breadcrumb>
      <b-steps
        :current="stepVal"
        direction="vertical"
        @change.self="stepChange"
      >
        <b-step title="基本信息">
          <a-card
            v-show="activeKey[0]"
            slot="description"
            v-loading="loading"
            :bordered="false"
          >
            <a-form-model
              ref="ruleForm"
              :model="formData"
              :rules="rules"
            >
              <a-row>
                <a-col span="8">
                  <!-- 编辑时才显示-->
                  <a-form-model-item label="物资盘点记录编码">
                    <BaseInput
                      v-model="formData.code"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="项目名称"
                    prop="projectId"
                  >
                    <SelectDownProject
                      v-model="formData.projectId"
                      :disabled="state === 3"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="编号"
                    prop="number"
                  >
                    <BSelect :request="getNumber"
                             v-model="formData.number"
                             :disabled="state === 3"
                             :init="false"
                             :form="formData"
                             :is-edit="formData.id !== null"
                             key-value="projectId"
                             :keys="['id','inventoryCodeAll']"
                    />
                    <!--                    <BaseInput-->
                    <!--                      v-model="formData.number"-->
                    <!--                      :disabled="state === 3"-->
                    <!--                    />-->
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="盘点时间"
                    prop="inventoryDate"
                  >
                    <a-date-picker
                      v-model="formData.inventoryDate"
                      value-format="YYYY-MM-DD"
                      :disabled="state === 3"
                      @change="getDate"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="创建人">
                    <BaseInput
                      v-model="formData.creatorName"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="创建时间">
                    <BaseInput
                      v-model="formData.createTime"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col>
                  <a-form-model-item
                    label="评估结论"
                    prop="evalConclusion"
                  >
                    <BaseTextarea
                      v-model="formData.evalConclusion"
                      :disabled="state === 3"
                      :auto-size="{ minRows: 3, maxRows: 5 }"
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form-model>
            <div class="pub-next-btn">
              <a-button
                v-if="state !== 3"
                type="primary"
                @click="temporaryStorage()"
              >
                保存草稿
              </a-button>
              <a-button
                type="primary"
                @click="temporaryStorage(true)"
              >
                下一步
              </a-button>
            </div>
          </a-card>
        </b-step>
        <b-step title="物资盘点明细表">
          <a-card
            v-if="activeKey[1]"
            slot="description"
            :bordered="false"
          >
            <detail
              :id="row ? row.id : null"
              ref="detail"
              :state="state"
            />
            <div class="pub-next-btn">
              <a-button
                type="primary"
                @click="previous"
              >
                上一步
              </a-button>
              <a-button
                type="primary"
                @click="next"
              >
                下一步
              </a-button>
            </div>
          </a-card>
        </b-step>
        <b-step title="相关附件">
          <a-card
            v-if="activeKey[2]"
            slot="description"
            :bordered="false"
          >
            <u-table
              :upload-list="addFile"
              :delete-url="fileDel"
              :is-show="state !== 3"
              :list-url="fileList"
              :business-id="row.id"
              business-code="MM01"
            />
            <div class="pub-next-btn">
              <a-button
                type="primary"
                @click="previous"
              >
                上一步
              </a-button>
            </div>
          </a-card>
        </b-step>
      </b-steps>
      <div class="pub-header-btn page-btn-right-top">
        <template v-if="state !== 3">
          <a-button
            type="primary"
            :loading="loading"
            @click="submit"
          >
            提交
          </a-button>
          <a-button
            type="primary"
            :loading="loading"
            @click="temporaryStorage"
          >
            保存
          </a-button>
        </template>
        <BasePrintButton
          v-if="formData.id && state == 3&&!isAudit"
          :before-print-fn="beforePrintFn"
          style="display: inline-block"
        />
        <a-button @click="handleClose">
          关闭
        </a-button>
      </div>
      <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
    </base-breadcrumb>
  </div>
</template>

<script>
import detail from '../components/detail/detail'
import { checkAdd, checkEdit, audit, addFile, fileList, fileDel, print,findListByMainId} from '@/api/material/inventory/check'
import SelectDownProject from '@/components/Select/SelectDownProject'
import Api from '@/api/material/inventory/checkPlan'
import dayjs from 'dayjs'

export default {
  name: 'a' + Date.now(),
  components: {
    detail,
    SelectDownProject
  },
  props: {
    isAudit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      beforePrintFn: async () => {
        let res = await print({ id: this.formData.id })
        return res.data.content
      },
      getNumber: () => {
        let params = { pageSize: 1000, pageNo: 1 }
        params.query = {
          auditStatus: 'PAST',
          // inventoryTime: dayjs(new Date()).format('YYYY-MM'),
          projectId: this.formData.projectId
        }
        return Api.findListByMain(params)
      },
      activeKey: [true, false, false, false, false, false, false],
      loading: false,
      state: Number(this.$route.query.state),
      // state: 2,
      isSubmit: false,
      row: this.$route.query.row,
      formData: {
        id: null,
        createTime: this.getNowTime(),
        creatorName: JSON.parse(sessionStorage.getItem('ycloud-user_info')).name,
        code: '',
        number: '',
        projectId: null,
        projectCode: '',
        inventoryDate: null,
        evalConclusion: ''
      },
      isNext: false,
      stepVal: 0,
      addFile: addFile(),
      fileDel: fileDel(),
      fileList: fileList(),
      rules: {
        projectId: { required: true, message: '项目名称不能为空', trigger: 'blur' },
        number: { required: true, message: '编号不能为空', trigger: 'blur' },
        inventoryDate: { required: true, message: '盘点时间不能为空', trigger: 'change' },
        evalConclusion: { required: true, message: '评估结论不能为空', trigger: 'blur' }
      },
       //获取流程配置值
        processConfig: null,
        //点击提交发送流程配置值
        setProcessConfig: null,
        businessId: null
    }
  },
  watch: {
    stepVal(newVal, oldVal) {
      this.$set(this.activeKey, newVal, true)
    },
    isAudit: {
      immediate: true,
      handler(val) {
        val && this.getDetail(this.$route.query.businessId)
        if (val) {
          this.state = 3
        }
      }
    },
  },
 async mounted() {
    if (this.state !== 1 && !this.isAudit) {
      this.getEditInfo()
      this.isSubmit = true
    }
   //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('mm_invertory')
    //this.id && this.getDetail()
  },
  methods: {
    getDetail(id){
      findListByMainId({id:id}).then((res)=>{
        if(res.code == 200){
           this.row = res.data;
           this.getEditInfo()
        }
      })
    },
    handleClose() {
      this.$close()
    },
    getDate: function(date, dateString) {
      this.formData.inventoryDate = dateString
    },
    projectChange: function(val) {
      let _this = this
      _this.project.map(function(item) {
        if (item.code === val) {
          _this.formData.projectCode = val
        }
      })
    },
    stepChange: function(val) {
      if (!this.row) {
        if (val) {
          this.$message.warning('切换步骤前请先填写基本信息')
          this.stepVal = 0
        }
      } else {
        if (!this.isNext) {
          this.$set(this.activeKey, val, !this.activeKey[val])
        }
      }
      this.isNext = false
    },
    next: function(val) {
      this.isNext = true
      this.stepVal++
    },
    previous: function() {
      this.isNext = true
      this.stepVal--
      if (this.stepVal < 0) {
        this.stepVal = 0
      }
    },
    // 获取编辑回显数据
    getEditInfo() {
      this.formData.id = this.row.id
      this.formData.code = this.row.code
      this.formData.createTime = this.row.createTime
      this.formData.creatorName = this.row.creatorName
      this.formData.projectId = this.row.projectId
      this.formData.projectCode = this.row.projectCode
      this.formData.number = this.row.number
      this.formData.inventoryDate = this.row.inventoryDate
      this.formData.evalConclusion = this.row.evalConclusion
      this.$console(this.row)
      this.$console(this.formData)
    },
    submit() {
       this.setProcessConfig = null;
      // this.save('approve');
      if (this.isSubmit) {
        this.submitApprovalConfirm(this.processConfig,(flag) => {
          if(!flag) {
            this.loading = false
            return
          }
          this.loading = true
          audit({
            baseId: this.row.id,
            auditStatus: this.row.auditStatus
          }).then(res => {
            this.loading = false
            if (res.code === this.SUCCESS_CODE) {
              this.$message.success('提交成功')
              //提交时，返回id
              this.businessId = this.row.id;
              this.setProcessConfig = this.processConfig;
            }
          })
        })
      } else {
        this.$message.warning('提交之前请先暂存')
      }
    },
    temporaryStorage(isNext) {
      if (this.state === 3) {
        this.next()
        return
      }
      this.$refs.ruleForm.validate((valid, object) => {
        if (valid) {
          this.loading = true
          if (this.state === 2 || this.row) {
            this.formData.id = this.row.id
            checkEdit(this.formData).then(res => {
              if (res.code === 200) {
                this.$message.success('暂存成功')
                this.isSubmit = true
                if (isNext) {
                  this.next()
                }
              }
              this.loading = false
            })
          } else {
            checkAdd(this.formData).then(res => {
              if (res.code === 200) {
                this.row = res.data
                this.$message.success('暂存成功')
                this.isSubmit = true
                this.getEditInfo()
                if (isNext) {
                  this.next()
                }
              }
              this.loading = false
            })
          }
        } else {
          this.$message.warning("请填写完所有必填项信息")
          return false
        }
      })
    }
  }
}
</script>
